package com.kfm.company.controller;

import com.kfm.company.model.Role;
import com.kfm.company.model.User;
import com.kfm.company.model.UserVO;
import com.kfm.company.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService service;

    @GetMapping("/login")
    public String login() {
        return "/user/login";
    }

    @PostMapping("/login")
    public ModelAndView login(User user, String captcha, HttpServletRequest request,
                              RedirectAttributes attributes, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        if (!CaptchaUtil.ver(captcha, request)) {
            mv.setViewName("redirect:/login");
            attributes.addFlashAttribute("msg", "验证码错误");
            return mv;
        }
        User login = service.login(user);
        if (login == null) {
            attributes.addFlashAttribute("msg", "登录失败");
            mv.setViewName("redirect:/login");
            return mv;
        }
        attributes.addFlashAttribute("msg", "登录成功");
        List<Role> roles = login.getRoles();
        int role = 0;
        for (Role r : roles) {
            if ("管理员".equals(r.getRoleName())) {
                role = 1;
                break;
            }
        }
        mv.setViewName("redirect:/user/index?role=" + role);
        session.setAttribute("loginUser", new UserVO(login));
        return mv;
    }

    @RequestMapping("/user/index")
    public ModelAndView index(Integer role) {
        ModelAndView mv = new ModelAndView("/user/index");
        mv.addObject("role", role);
        return mv;
    }

    @RequestMapping("/user/list")
    public ModelAndView list() {
        // TODO 查询所有用户
        ModelAndView mv = new ModelAndView("/user/list");
        return mv;
    }
}
